'use strict';
const axios = require('axios');
const urljoin = require('url-join');
const semver = require('semver');
function getDefaultRegistry(isOriginal = false) {
  return isOriginal
    ? 'https://registry.npmjs.org'
    : 'https://registry.npmmirror.com';
}
function getNpmInfo(npmName, registry) {
  if (!npmName) {
    return null;
  }
  const registryUrl = registry || getDefaultRegistry();
  const npmInfoUrl = urljoin(registryUrl, npmName);
  return axios
    .get(npmInfoUrl)
    .then((res) => {
      if (res.status === 200) {
        return res.data;
      }
      return null;
    })
    .catch((err) => {
      return Promise.reject(err);
    });
  // https://registry.npmmirror.com/axios
  // https://registry.npmjs.org/@dpx-cli-dev/cor
}
async function getNpmVersions(npmName, registry) {
  const data = await getNpmInfo(npmName, registry);
  if (data) {
    return Object.keys(data.versions);
  } else {
    return [];
  }
}
function getSemverVersions(baseVersion, versions) {
  const arr = versions.filter((version) =>
    semver.satisfies(version, `^${baseVersion}`)
  );
  return semver.rsort(versions);
  // .sort((a, b) => semver.gt(a, b));
}
async function getNpmSemverVersion(baseVersion, npmName, registry) {
  const versions = await getNpmVersions(npmName, registry);
  const newVersions = getSemverVersions(baseVersion, versions);
  if (newVersions && newVersions.length) {
    return newVersions[0];
  }
}
async function getNpmLatestVersion(npmName, registry) {
  let versions = await getNpmVersions(npmName, registry);
  if (versions) {
    return semver.rsort(versions)[0];
    // return versions.sort((a, b) => semver.gt(b, a))[0];
  }
  return null;
}
module.exports = {
  getNpmInfo,
  getNpmVersions,
  getNpmSemverVersion,
  getDefaultRegistry,
  getNpmLatestVersion,
};
